package com.imooc.Interceptor;

import com.imooc.base.BaseInfoProperties;

import com.imooc.exceptions.GraceException;
import com.imooc.grace.result.GraceJSONResult;
import com.imooc.grace.result.ResponseStatusEnum;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Slf4j
public class UserTokenInterceptor extends BaseInfoProperties implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String userId = request.getHeader("headerUserId");
        String userToken = request.getHeader("headerUserToken");

       if (StringUtils.isNotBlank(userToken) && StringUtils.isNotBlank(userId)) {//判断会话信息是否存在
           String redisToken = redis.get(REDIS_USER_TOKEN + ":" + userId);
           if (StringUtils.isBlank(redisToken)) {  //判断redis 会话信息是否存在 不存在去要重新登录
               GraceException.display(ResponseStatusEnum.UN_LOGIN);
               return false;
           } else {
               //  redis 会话信息存在  就 比较Token 是否一致 如果不一致 表示用户在别的手机登录
               if (!redisToken.equalsIgnoreCase(userToken)) {  //不相等说明在其他设备登录
                   GraceException.display(ResponseStatusEnum.TICKET_INVALID);
                   return false;
               }
           }
       }else {
           GraceException.display(ResponseStatusEnum.UN_LOGIN);
           return false;
       }
        return  true;
    }
}
